<template>
  <div class="kva-container flex1">
    <div class=" ml15">
      <div class="kva-form-search">
        <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm">
          <el-form-item>
            <el-button type="primary" icon="plus" @click="handleBindUser">绑定用户</el-button>
          </el-form-item>
          <el-form-item  v-if="selectIds.length > 0">
            <el-button type="danger" icon="Delete"  @click="handleBatchDels">批量回收站</el-button>
          </el-form-item>
          <el-form-item label="用户编号：" prop="uuid">
            <el-input v-model="queryParams.uuid" placeholder="请输入用户编号..." maxlength="100" clearable />
          </el-form-item>
          <el-form-item label="用户手机：" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入用户手机..." maxlength="20" clearable />
          </el-form-item>
          <el-form-item label="支付方式" prop="payMethod">
            <el-select v-model="queryParams.payMethod" class="m-2" placeholder="请选择" clearable  @change="handleSearch">
              <el-option
                  v-for="item in [
                  { value: 1, label: '微信' },
                  { value: 2, label: '支付宝' },
                  { value: 3, label: '兑换码' }
                ]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="兑换码：" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输入兑换码..." maxlength="100" clearable />
          </el-form-item>
          <el-form-item label="流水号：" prop="orderno">
            <el-input v-model="queryParams.orderno" placeholder="请输入兑换码..." maxlength="100" clearable />
          </el-form-item>
          <el-form-item label="关键词：" prop="keyword">
            <el-input v-model="queryParams.keyword" placeholder="请输入标题，昵称，用户名..." maxlength="20" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click.prevent="handleSearch">搜索</el-button>
            <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div  style="background: #fff;border-radius: 8px;padding: 10px">
      <div v-if="selectIds.length>0" class="mb10">
        <el-alert
            size="small"
            @close="handleAlertClose"
            :title="'选中了（' + selectIds.length + '）项数据'"
            type="success"
            show-icon
        />
      </div>
      <el-table
          v-loading="tableLoading"
          ref="tableRef"
          row-key="id"
          :data="tableData"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
          :height="tableHeight"
      >
        <el-table-column fixed type="selection" width="55"/>
        <el-table-column   width="120" label="封面">
          <template v-slot="scope">
            <img :src="scope.row.cover" alt="" style="width:80px">
          </template>
        </el-table-column>
        <el-table-column  label="资源信息"  width="400">
          <template v-slot="scope">
            <div><strong>资源编号：</strong>{{scope.row.opid}}</div>
            <div><strong>资源标题：</strong>{{scope.row.title}}</div>
            <div><strong>资源金额：</strong>{{scope.row.price}}</div>
            <div><strong>支付时间：</strong>{{ formatTimeToStr(scope.row.createTime) }}</div>
            <div>
              <strong>支付方式：</strong>
              <span v-if="scope.row.payMethod==1">微信</span>
              <span v-if="scope.row.payMethod==2">支付宝</span>
              <span v-if="scope.row.payMethod==3">兑换码</span>
              <span v-if="scope.row.payMethod==4">人工绑定</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column  label="支付用户"  width="400">
          <template v-slot="scope">
            <div><strong>支付用户：</strong>{{scope.row.username}}</div>
            <div><strong>用户昵称：</strong>{{scope.row.nickname}}</div>
            <div><strong>用户编号：</strong>{{scope.row.uuid}}</div>
            <div><strong>用户手机：</strong>{{scope.row.phone}}</div>
            <div><strong>收货地址：</strong>{{scope.row.address}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="orderno" label="支付订单号" align="center" width="250"></el-table-column>
        <el-table-column prop="tradeno" label="订单流水号" align="center" width="250"></el-table-column>
        <el-table-column prop="code" label="兑换码" align="center" width="250"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="100">
          <template #default="scope">
            <el-button icon="remove" type="danger" size="small" @click.stop="handleDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="kva-pagination-box center">
        <el-pagination
            :current-page="queryParams.pageNo"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
      </div>
  </div>
  </div>
</template>
<script setup>
import KVA from '@/utils/kva.js'
import { formatTimeToStr } from '@/utils/date.js'
import { findPages, removeById, bindUserOrder,batchRemoves } from '@/api/special/order.js'
// 搜索属性定义
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  opid: '',
  orderno: '',
  code: '',
  phone: '',
  uuid: '',
  keyword: ''
})

// 定义响应式得列表数据容器
const tableRef = ref({})
const tableData = ref([])
const tableLoading = ref(false)
const searchForm = ref({})
const total = ref(0)
const pages = ref(0)
const selectIds = ref([])
const showAlert = ref(false)
const tableHeight = ref('calc(100vh - 335px)')
// 加载数据
const handleLodeData = async (opid) => {
  tableLoading.value = true
  queryParams.opid = opid
  const resp = await findPages(queryParams)
  tableData.value = resp.data.records
  total.value = resp.data.total * 1
  pages.value = resp.data.pages * 1
  tableLoading.value = false
}


// 改变行颜色
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.loadmore == 1) {
    return 'hot-row'
  }
  return ''
}



// 清空选择
const handleAlertClose = () => {
  showAlert.value = false
  tableRef.value.clearSelection()
}


/**
 * 选择删除的元素
 * @param rows
 */
const handleSelectionChange = (rows) => {
  showAlert.value = rows.length > 0
  selectIds.value = rows.map((c) => c.id)
  tableHeight.value = rows.length > 0 ? 'calc(100vh - 310px)' : 'calc(100vh - 265px)'
}


// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  handleLodeData(queryParams.opid)
}

// 重置
const handleReset = () => {
  searchForm.value.resetFields()
  handleSearch(queryParams.opid)
}

// 分页size更改
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  handleLodeData(queryParams.opid)
}

// 分页pageNo更改
const handleCurrentChange = (pno) => {
  queryParams.pageNo = pno
  handleLodeData(queryParams.opid)
}

// 删除
const handleDel = (row) => {
  KVA.confirm('警告', '<strong>您确定要执行此次操作吗？</strong>', { icon: 'success' }).then(async () => {
    await removeById(row.id)
    KVA.notifySuccess('删除成功!')
    handleLodeData(queryParams.opid)
  })
}

/**
 * 批量加入回收站
 */
const handleBatchDels = () => {
  if (selectIds.value && selectIds.value.length == 0) {
    KVA.notifyError('请选择一个项进行操作！')
    return
  }

  KVA.confirm('警告', '<strong>您确定要执行此次【批量删除】操作吗？</strong>', { icon: 'success' }).then(
      async () => {
        const ids = selectIds.value.join(',')
        await batchRemoves(ids)
        KVA.notifySuccess('批量恢复成功!')
        handleLodeData(queryParams.opid)
      }
  )
}

const handleBindUser = async ()=>{
  if(!queryParams.uuid){
    KVA.error("请输入用户编号！")
    return;
  }
  await bindUserOrder(queryParams.uuid,queryParams.opid)
  KVA.success("绑定成功")
  handleLodeData(queryParams.opid)
}

defineExpose({
  handleLodeData
})

</script>
